<?php

class DeliveriesController extends AppController {

  var $helpers = array("Html","Text","Javascript","Ajax");
  
  function view() {
    $this->set('deliveries',$this->Delivery->findAll());
  }
	
	function current() {
		$this->layout = 'ajax';
    $ds = date('Y-m-d H:i:s');
		$this->set('delivery',$this->Delivery->find("edit_open < '" . $ds . "' AND '" . $ds . "' < pickup_closed"));
	}
	
	function getCurrentDelivery() {
		return $this->Delivery->getCurrent();
	}
  
  function add() {
    if ($this->checkSession()) {
      if($this->checkLevel(AUTH_ADMIN)) {
      } else {
        $this->notAuth();
      }
    } else {
      $this->forceLogin();
    }
    if (!empty($this->data['Delivery'])) {
      //try to save
      $dates = array();
      foreach(array("edit_open","order_open","order_closed","delivery_open","pickup_open") as $type) {
        $dates[$type] = $this->data['Delivery'][$type]['year'] . '-' . $this->data['Delivery'][$type]['month'] . '-' . $this->data['Delivery'][$type]['day'];
      }
      $times = array();
      foreach(array("delivery_open","delivery_closed","pickup_open","pickup_closed") as $type) {
        if ($this->data['Delivery'][$type]['meridian'] == 'am') {
          if ($this->data['Delivery'][$type]['hour'] == 12) {
            $this->data['Delivery'][$type]['hour'] = '00';
          }
        } else {
          if ($this->data['Delivery'][$type]['hour'] != 12) {
            $this->data['Delivery'][$type]['hour'] = $this->data['Delivery'][$type]['hour'] + 12;
          }
        }
        $times[$type] = $this->data['Delivery'][$type]['hour'] . ':' . $this->data['Delivery'][$type]['min'] . ':00';
      }
      foreach(array("edit","order","delivery","pickup") as $type) {
        $t = (isset($times[$type . '_open'])) ? $times[$type . '_open'] : '00:00:00';
        $d = $dates[$type . '_open'];
        $this->data['Delivery'][$type . '_open'] = $d . ' ' . $t;
        if (isset($dates[$type . '_closed']) or isset($times[$type . '_closed'])) {
          $t = (isset($times[$type . '_closed'])) ? $times[$type . '_closed'] : '00:00:00';
          $d = (isset($dates[$type . '_closed'])) ? $dates[$type . '_closed'] : $d;
          $this->data['Delivery'][$type . '_closed'] = $d . ' ' . $t;
        }
      }
      if ($this->Delivery->save($this->data)) {
        $this->Session->setFlash("Delivery Set");
        $this->redirect('/members/menu');
      }
      //$this->set('poster',array($this->data,$dates,$times));
    } else {
      
    }
  }
  
  function currentId(){
    return $this->currentId;
  }
  
  function isOpen(){
    return Configure::read('Delivery.is_open');
  }
  
  function afterOpen(){
    return Configure::read('Delivery.after_open');
  }


}
